package com.gz.university.crm.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.gz.university.crm.dao.ISysMenuPrivilegeDao;
import com.gz.university.crm.entity.SysMenuPrivilege;
import com.gz.university.crm.service.ISysMenuPrivilegeService;

@Service(value = ISysMenuPrivilegeService.SERVICE_NAME)
@Transactional(readOnly = true)
public class SysMenuPrivilegeServiceImpl implements ISysMenuPrivilegeService {
	private ISysMenuPrivilegeDao sysMenuPrivilegeDao;

	public ISysMenuPrivilegeDao getSysMenuPrivilegeDao() {
		return sysMenuPrivilegeDao;
	}

	@Resource(name = ISysMenuPrivilegeDao.DAO_NAME)
	public void setSysMenuPrivilegeDao(ISysMenuPrivilegeDao sysMenuPrivilegeDao) {
		this.sysMenuPrivilegeDao = sysMenuPrivilegeDao;
	}

	@Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, readOnly = false)
	@Override
	public void updateMenu(Integer roleId, String[] menuModules) {
		// TODO Auto-generated method stub
		// 删除权限组对应的
        if (roleId!=null&&menuModules!=null&&menuModules.length>0) {
			//查出该权限Id所包含的菜单资源
        	String hql="from SysMenuPrivilege s where s.roleId is :roleId";
        	Map<String, Object> params=new HashMap<>();
        	params.put("roleId", roleId);
        	List<SysMenuPrivilege> sysMenuPrivileges=this.sysMenuPrivilegeDao.find(hql, params);
        	for (SysMenuPrivilege o : sysMenuPrivileges) {
				this.sysMenuPrivilegeDao.delete(o);
			}
		}
		// 增加菜单权限到权限组中
		if (roleId != null && menuModules != null && menuModules.length > 0) {
			for (int i = 0; i < menuModules.length; i++) {
				if (StringUtils.isNotBlank(menuModules[i])) {
					String[] strings = menuModules[i].split(",");
					SysMenuPrivilege o = new SysMenuPrivilege();
					o.setRoleId(roleId);
					o.setMenuModule(strings[0]);
					o.setMenuPrivilege(strings[1]);
					this.sysMenuPrivilegeDao.save(o);
				}
			}
		}
	}

	@Override
	public List<SysMenuPrivilege> findSysMenuPrivilegesByRoleId(Integer roleId) {
		// TODO Auto-generated method stub
		if (roleId != null) {
			final String hql = "from SysMenuPrivilege s where s.roleId is :roleId";
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("roleId", roleId);
			return this.sysMenuPrivilegeDao.find(hql, params);
		}
		return null;
	}

	@Override
	public List<SysMenuPrivilege> findAll() {
		// TODO Auto-generated method stub
		final String hql="from SysMenuPrivilege s order by s.roleId";
		return this.sysMenuPrivilegeDao.find(hql);
	}

}
